package com.ludomancy.gamelib;


import java.awt.Point;


public class Viewport
{
	private int worldWidth;
	private int worldHeight;
	private int viewWidth;
	private int viewHeight;
	private int scrollMargin;
	
	public int cameraX;
	public int cameraY;
	
	public Viewport(int worldWidth, int worldHeight, int viewWidth, int viewHeight, int scrollMargin)
	{
		this.worldHeight = worldHeight;
		this.worldWidth = worldWidth;
		this.viewHeight = viewHeight;
		this.viewWidth = viewWidth;
		this.scrollMargin = scrollMargin;
		cameraX = viewWidth/2;
		cameraY = viewHeight/2;
	}
	
	public void updateCamera(int worldX, int worldY)
	{
		// are we inside the non-scrolling area?
		int offsetX = worldX - cameraX;
		int offsetY = worldY - cameraY;
		int distToBorderX = viewWidth/2 - Math.abs(offsetX);
		int distToBorderY = viewHeight/2 - Math.abs(offsetY);
		if(distToBorderX < scrollMargin)
		{
			int diffToScrollMargin = distToBorderX - scrollMargin;
			cameraX += diffToScrollMargin * -MathHelper.sign(offsetX);
		}
		if(distToBorderY < scrollMargin)
		{
			int diffToScrollMargin = distToBorderY - scrollMargin;
			cameraY += diffToScrollMargin * -MathHelper.sign(offsetY);
		}
		
		// snapping
		if(cameraX < viewWidth/2)
			cameraX = viewWidth/2;
		if(cameraX + viewWidth/2 > worldWidth)
			cameraX = worldWidth - viewWidth/2;
		if(cameraY < viewHeight/2)
			cameraY = viewHeight/2;
		if(cameraY + viewHeight/2 > worldHeight)
			cameraY = worldHeight - viewHeight/2;
	}
	
	public Point getWorldTopLeft()
	{
		return new Point(cameraX - viewWidth/2, cameraY - viewHeight/2);
	}
}
